package com.stx.jeepay.payment.task;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.stx.jeepay.core.entity.RefundOrderEntity;
import com.stx.jeepay.core.service.RefundOrderService;
import com.stx.jeepay.payment.service.ChannelOrderReissueService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.scheduling.annotation.Scheduled;
import org.springframework.stereotype.Component;

/**
 * 补单定时任务(退款单)
 */
@Slf4j
@Component
public class RefundOrderReissueTask {

    private static final int QUERY_PAGE_SIZE = 100; //每次查询数量

    @Autowired
    private RefundOrderService refundOrderService;
    @Autowired
    private ChannelOrderReissueService channelOrderReissueService;

    @Scheduled(cron = "0 0/1 * * * ?") // 每分钟执行一次
    public void start() {
        //查询条件： 退款中的订单
        LambdaQueryWrapper<RefundOrderEntity> queryWrapper = new LambdaQueryWrapper<>();
        queryWrapper.eq(RefundOrderEntity::getState, RefundOrderEntity.STATE_ING);

        int currentPageIndex = 1; //当前页码
        while (true) {
            try {
                IPage<RefundOrderEntity> page =
                        refundOrderService.page(new Page<>(currentPageIndex, QUERY_PAGE_SIZE), queryWrapper);

                if (page == null || page.getRecords() == null || page.getRecords().isEmpty()) {
                    // 没查到结果直接退出
                    break;
                }

                for (RefundOrderEntity record : page.getRecords()) {
                    channelOrderReissueService.processRefundOrder(record);
                }

                //已经到达页码最大量，无需再次查询
                if (page.getPages() <= currentPageIndex) {
                    break;
                }
                currentPageIndex++;
            } catch (Exception e) {
                // 异常直接退出
                log.error("error", e);
                break;
            }
        }
    }
}
